﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Eqwww.App.Authorize;
using Eqwww.App.SystemManage;
using Eqwww.Code;
using Eqwww.Domain.Models.SystemManage;
using Eqwww.Web.Areas.SystemManage.Models.ModuleButton;
using Microsoft.AspNetCore.Mvc;

namespace Eqwww.Web.Areas.SystemManage.Controllers
{
    [Area("SystemManage")]
    public class ModuleButtonController : ControllerBase
    {
        private ModuleButtonApp _moduleButtonApp;
        private ModuleApp _moduleApp;
        private AuthorizeApp _authorizeApp;
        private IMapper _mapper;

        public ModuleButtonController(ModuleButtonApp moduleButtonApp
            , AuthorizeApp authorizeApp
            , ModuleApp moduleApp
            , IMapper mapper)
        {
            _authorizeApp = authorizeApp;
            _moduleButtonApp = moduleButtonApp;
            _moduleApp = moduleApp;
            _mapper = mapper;
        }

        [AuthFilter]
        public IActionResult Index(string moduleId)
        {
            var currentParentCode = "SystemManage_ModuleButton";
            ViewData["SelectedButtons"] = _authorizeApp.GetAuthorizedModuleButtonsByParentCode(User, currentParentCode, ModuleButtonPosition.Selected);
            ViewData["InitialButtons"] = _authorizeApp.GetAuthorizedModuleButtonsByParentCode(User, currentParentCode, ModuleButtonPosition.Initial);

            return View();
        }

        [AuthFilter]
        public IActionResult IndexGridJson(string moduleId)
        {
            var data = _moduleButtonApp.GetTreeGridByModuleId(moduleId);
            var treeList = new List<TreeGridModel>();
            foreach (var item in data)
            {
                TreeGridModel treeModel = new TreeGridModel();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                treeModel.id = item.Id;
                treeModel.isLeaf = hasChildren;
                treeModel.parentId = item.ParentId;
                treeModel.expanded = hasChildren;
                treeModel.entityJson = item.ToJson();
                treeList.Add(treeModel);
            }
            return Content(treeList.TreeGridJson());
        }

        [AuthFilter]
        public IActionResult Details(string id)
        {
            if (id == null)
            {
                return NotFoundObject();
            }

            var moduleButtonModel = _moduleButtonApp.Get(id, false, true);
            if (moduleButtonModel == null)
            {
                return NotFoundObject();
            }

            ViewData["RelatedStrategorys"] = _moduleButtonApp.GetRelatedStrategorysByButtonId(id);

            return View(moduleButtonModel);
        }

        [AuthFilter]
        public IActionResult Create(string moduleId)
        {
            var module = _moduleApp.Get(moduleId);
            if (module != null)
            {
                ViewData["CodePrefix"] = module.Code + "_";
            }
            return View();
        }


        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult Create([Bind("Code,Name,ParentId,ModuleId,ModuleButtonPosition,JsAction,Url,ModuleButtonOpenType,SortCode,Icon,ModuleButtonShowType,ModuleButtonColorType")] CreateViewModel createViewModel)
        {
            if (ModelState.IsValid)
            {/*
                var model = new ModuleButtonModel
                {
                    
                    Code = createViewModel.Code,
                    Name = createViewModel.Name,
                    ParentId = createViewModel.ParentId,
                    ModuleId = createViewModel.ModuleId,
                    ModuleButtonPosition = createViewModel.ModuleButtonPosition,
                    JsAction = createViewModel.JsAction,
                    Url = createViewModel.Url,
                    ModuleButtonOpenType = createViewModel.ModuleButtonOpenType,
                    SortCode = createViewModel.SortCode,
                    Icon = createViewModel.Icon,
                    ModuleButtonShowType = createViewModel.ModuleButtonShowType,
                    ModuleButtonColorType = createViewModel.ModuleButtonColorType
                    
                };
                */
                var model = _mapper.Map<ModuleButtonModel>(createViewModel);
                return Json(_moduleButtonApp.Create(model));

            }

            return Json(Common.ModelStateErrorResult(ModelState));
        }

        [AuthFilter]
        public IActionResult Edit(string id)
        {
            if (id == null)
            {
                return NotFoundObject();
            }

            var model = _moduleButtonApp.Get(id, false, true);
            if (model == null)
            {
                return NotFoundObject();
            }
            if (model.IsSystem == true)
                return ErrorView("系统按钮不允许修改！");
            var parentName = string.Empty;
            if (!string.IsNullOrEmpty(model.ParentId))
            {
                var parent = _moduleButtonApp.Get(model.ParentId, true, false);
                if (parent != null)
                    parentName = parent.Name;
            }
            var viewModel = _mapper.Map<EditViewModel>(model);
            viewModel.ParentName = parentName;
            return View(viewModel);
        }


        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(string id, [Bind("Id,Code,Name,ParentId,ModuleId,ModuleButtonPosition,JsAction,Url,ModuleButtonOpenType,SortCode,Icon,ModuleButtonShowType,ModuleButtonColorType")] EditViewModel viewModel)
        {

            if (id != viewModel.Id)
            {
                return Error("GET ID和POST ID不一致！");
            }
            if (ModelState.IsValid)
            {
                var model = _moduleButtonApp.Get(id);
                _mapper.Map(viewModel, model);
                return Json(_moduleButtonApp.Update(model));
            }
            return Json(Common.ModelStateErrorResult(ModelState));
        }


        [HttpPost, ActionName("Delete")]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteConfirmed(string id)
        {
            return Json(_moduleButtonApp.Remove(id));
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult UpdateIsSystem(string id)
        {
            return Json(_moduleButtonApp.UpdateIsSystem(id, true));
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult UpdateIsNotSystem(string id)
        {
            return Json(_moduleButtonApp.UpdateIsSystem(id, false));
        }

        public IActionResult TreeCollapse(string moduleId)
        {
            ViewData["Items"] = _moduleButtonApp.GetTreeCollapseItems(moduleId);
            return View();
        }

        [AuthFilter]
        public IActionResult CloneButton()
        {
            ViewData["Items"] = _moduleButtonApp.GetModuleAndButtonTreeCollapseToggleList();
            return View();
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult CloneButtonSubmit(string moduleId, string parentId, string permissions)
        {
            var ps = string.IsNullOrEmpty(permissions) ? new string[] { } : permissions.Split(',');
            return Json(_moduleButtonApp.CloneButtons(moduleId, parentId, ps));
        }

        public IActionResult InitialButtons(string moduleId)
        {
            var module = _moduleApp.Get(moduleId);
            if (module == null)
                return Error("指定模块不存在！");

            if (_moduleButtonApp.IsModuleHasButtons(moduleId))
                return Error("当前模块包含按钮，不能执行按钮初始化操作");

            var buttons = new ModuleButtonModel[]
            {
                new ModuleButtonModel
                    {
                        Code=module.Code+"_Create",
                         Name="新建",
                         Icon="add",
                         JsAction="btn_create()",
                         ModuleButtonOpenType=ModuleButtonOpenType.Pop,
                         ModuleButtonPosition=ModuleButtonPosition.Initial,
                         ModuleId=module.Id,
                         SortCode=100,
                         Url=string.IsNullOrEmpty(module.Url)?"/Create":module.Url+"/Create",
                         ModuleButtonShowType=ModuleButtonShowType.TextAndIcon,
                         ModuleButtonColorType=ModuleButtonColorType.ColorTheme,
                         Layer=0
                    },
                    new ModuleButtonModel
                    {
                        Code=module.Code+"_Edit",
                         Name="修改",
                         Icon="edit",
                         JsAction="btn_edit()",
                         ModuleButtonOpenType=ModuleButtonOpenType.Pop,
                         ModuleButtonPosition=ModuleButtonPosition.Selected,
                         ModuleId=module.Id,
                         SortCode=200,
                         Url=string.IsNullOrEmpty(module.Url)?"/Edit":module.Url+"/Edit",
                         ModuleButtonShowType=ModuleButtonShowType.TextAndIcon,
                         ModuleButtonColorType=ModuleButtonColorType.ColorTheme,
                         Layer=0
                    },
                    new ModuleButtonModel
                    {
                        Code=module.Code+"_Details",
                         Name="查看",
                         Icon="remove_red_eye",
                         JsAction="btn_details()",
                         ModuleButtonOpenType=ModuleButtonOpenType.Pop,
                         ModuleButtonPosition=ModuleButtonPosition.Selected,
                         ModuleId=module.Id,
                         SortCode=300,
                         Url=string.IsNullOrEmpty(module.Url)?"/Details":module.Url+"/Details",
                         ModuleButtonShowType=ModuleButtonShowType.TextAndIcon,
                         ModuleButtonColorType=ModuleButtonColorType.ColorTheme,
                         Layer=0
                    },
                    new ModuleButtonModel
                    {
                        Code=module.Code+"_Delete",
                         Name="删除",
                         Icon="remove_circle_outline",
                         JsAction="btn_delete()",
                         ModuleButtonOpenType=ModuleButtonOpenType.Pop,
                         ModuleButtonPosition=ModuleButtonPosition.Selected,
                         ModuleId=module.Id,
                         SortCode=400,
                         Url=string.IsNullOrEmpty(module.Url)?"/Delete":module.Url+"/Delete",
                         ModuleButtonShowType=ModuleButtonShowType.TextAndIcon,
                         ModuleButtonColorType=ModuleButtonColorType.ColorDanger,
                         Layer=0
                    }
            };

            return Json(_moduleButtonApp.CreateRange(buttons));
        }
    }
}
